package by.grsu.hdm.model.ihomedevice.devices;

import java.util.ArrayList;
import java.util.List;

import by.grsu.hdm.exception.EmptyTrackListException;
import by.grsu.hdm.model.ihomedevice.HomeDevice;
import by.grsu.hdm.model.ihomedevice.behavior.IPlayer;

public class MediaPlayer extends HomeDevice implements IPlayer {

	private List<String> tracks = new ArrayList<String>();

	public List<String> getTracks() {
		return tracks;
	}

	private int currentTrackIndex;

	protected MediaPlayer() {
	}

	public MediaPlayer(String id) {
		super(id);
		currentTrackIndex = 0;
	}

	public String addTrack(String track) {
		if (isOn) {
			tracks.add(track);
			return "Track \"" + track + "\" is added";
		}
		return turnedOff;
	}

	@Override
	public String play() throws EmptyTrackListException {
		if (isOn) {
			try {
				return tracks.get(currentTrackIndex) + " is now playing";
			} catch (Exception e) {
				throw new EmptyTrackListException();
			}
		}
		return turnedOff;
	}

	public String play(String track) {
		if (isOn) {
			currentTrackIndex = tracks.indexOf(track);
			try {
				return play();
			} catch (EmptyTrackListException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return turnedOff;
	}

	@Override
	public String stop() throws EmptyTrackListException {
		if (isOn) {
			try {
				return tracks.get(currentTrackIndex) + " is stoped";
			} catch (Exception e) {
				throw new EmptyTrackListException();
			}
		}
		return turnedOff;
	}

	@Override
	public String next() throws EmptyTrackListException {
		if (isOn) {
			try {
				if (currentTrackIndex == tracks.size() - 1)
					currentTrackIndex = -1;
				currentTrackIndex++;
				return play();
			} catch (Exception e) {
				throw new EmptyTrackListException();
			}
		}
		return turnedOff;
	}

	@Override
	protected void afterTurningOn() {
		isOn = true;
	}

	@Override
	protected void beforeTurningOff() {
		isOn = false;
	}
}
